package com.atg.atgchat.init.aspect;

import cn.hutool.core.util.StrUtil;
import com.atg.atgchat.init.annotation.RedissonLock;
import com.atg.atgchat.init.common.utils.SpElUtils;
import com.atg.atgchat.init.user.service.LockService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/*
author: atg
time: 2025/1/17 14:34
*/
@Slf4j
@Aspect
@Component
@Order(0) //确保比事务注解先执行
public class RedissonLockAspect {
    @Resource
    private LockService lockService;

    @Around("@annotation( com.atg.atgchat.init.annotation.RedissonLock)")
    public Object around(ProceedingJoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        RedissonLock annotation = method.getAnnotation(RedissonLock.class);
        String prefix = StrUtil.isBlank(annotation.prefixKey()) ? SpElUtils.getMethodKey(method) : annotation.prefixKey();
        String key = SpElUtils.parseSpEl(method, joinPoint.getArgs(), annotation.key());
        return lockService.executeLock(prefix + ":"+key, annotation.waitTime(), annotation.unit(), joinPoint::proceed);

    }
}
